//
//  HomeViewController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "HomeViewController.h"
#import "DrawingViewController.h"
#import "HomeFlowLayout.h"
#import "UIBarButtonItem+Extension.h"
#import "QRCoderViewController.h"
#import "SearchGatewayButton.h"
#import "ConnectGatewayController.h"
#import "NewDeviceView.h"
#import "MeViewController.h"
#import "DataManager.h"
#import "MQTTSessionManager.h"
#import "RoomModel.h"
#import "MQTTCoverTool.h"
#import "ZTDevice.h"
#import "UnboundGatewayView.h"
#import "YSCommon.h"
#import "UIView+Frame.h"
#import "UIView+HUD.h"
#import "XAIGateway.h"
#import "CommonUtils.h"
#import "YSHUD.h"

// 默认标题间距
static CGFloat const margin = 20.0f;
static NSString *const kZTRoomCellReuseIdentifierID = @"kZTRoomCellReuseIdentifierID";
CGFloat const kTitleScrollViewH = 48;
#define kTitleFont [UIFont systemFontOfSize:15]

@interface HomeViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
DataManagerRefreshDelegate
>
//@property(nonatomic, strong)NSMutableArray *titleArray;
/**标题高度*/
@property (nonatomic, assign) CGFloat titleHeight;
/** 整体内容View 包含标题好内容滚动视图 */
@property (nullable, nonatomic, strong) UIView *contentView;
/** 标题滚动视图 */
@property (nullable, nonatomic, strong) UIScrollView *titleScrollView;
/** 内容滚动视图 */
@property (nullable, nonatomic, strong) UICollectionView *contentScrollView;
/** 内容滚动视图 */
@property (nullable, nonatomic, strong) HomeFlowLayout *flowLayout;
/* 是否初始化 */
@property (nonatomic, assign) BOOL isInitial;
/** 下标视图 */
@property (nullable, nonatomic, weak) UIView *underLine;
/** 所以标题宽度数组 */
@property (nullable, nonatomic, strong) NSMutableArray *titleWidths;
/** 所以标题控件 */
@property (nullable, nonatomic, strong) NSMutableArray *titleLabels;
/** 标题间距 */
@property (nonatomic, assign) CGFloat titleMargin;
/** 记录是否点击 */
@property (nonatomic, assign) BOOL isClickTitle;
/** 计算上一次选中角标 */
@property (nonatomic, assign) NSInteger selIndex;
/** 记录是否在动画 */
@property (nonatomic, assign) BOOL isAniming;
/** 记录上一次内容滚动视图偏移量 */
@property (nonatomic, assign) CGFloat lastOffsetX;
@property (nullable, nonatomic, strong) UIColor *titleScrollViewColor;
/**标题字体*/
@property (nullable, nonatomic, strong) UIFont *titleFont;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nullable, nonatomic, strong) NSMutableArray *m_arrayRoomList;
@property (nullable, nonatomic, strong) UnboundGatewayView *mViewUnboundGateway;
@property (nullable, nonatomic, strong) UIView* guideView;
@property (nullable, nonatomic, strong) UIView* guideBackgroundView;
@property (nullable, nonatomic, strong) UIImageView* guideImg;

@property (nullable, nonatomic, strong) UIView* leftBtnbackgroundView;
@property (nullable, nonatomic, strong) UIImageView* leftBtnImageView;

@property (nullable, nonatomic, strong) UINavigationBar* navigationBar;
@property (nullable, nonatomic, strong) UINavigationItem *titleItem;
@end

@implementation HomeViewController

#pragma mark - life cycle

- (void)dealloc
{
    debugLogInfo(@"HomeViewController dealloc.....");
    self.contentScrollView = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [kDataManager removeRefreshDelegate:self];
    [kDataManager removeGatewayRefreshDelegate:self];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubviews];
    [self initAllViewController];
    [self freshRoom];
    [self setupNotification];
    [kDataManager addRefreshDelegate:self];
    [kDataManager addGatewayRefreshDelegate:self];
    [self initFirstGuideMe];
    kMQTTSessionManager.isSHowHomeed = true;
    [self showOfflineMessage];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


#pragma mark - DataManagerRefreshDelegate

- (void)gatewayRefresh:(DataManager *)manager callbackType:(GatewayCallbackType)callbackType {
    switch (callbackType) {
        case GatewayCallbackTypeName:
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self refreshGateway];
            });
        }
            break;
        case GatewayCallbackTypePower:
        {
            
        }
            break;
        case GatewayCallbackTypeConnectStatus:
        {
            [self deviceDataRefresh];
        }
            break;
        case GatewayCallbackTypeLinkage:
        {
            
        }
            break;
        default:
            break;
    }
}
- (void)deviceRefresh:(DataManager *)manager callbackType:(DeviceCallbackType)callbackType
{
    switch (callbackType)
    {
        case DeviceCallbackTypeName:
        {
            [self devNameChangeRefresh:kDataManager];
        }
            break;
        case DeviceCallbackTypeConnectStatus:
        case DeviceCallbackTypeStatus:
        {
            [self deviceDataRefresh];
        }
            break;
        case DeviceCallbackTypePower:
        {
            
        }
            break;
        default:
            break;
    }
}
- (void)devNameChangeRefresh:(DataManager *)manager
{
    [kDataManager devlistLock];
    for (ZTDevice *dev in kDataManager.deviceListenList)
    {
        if (dev.apsn != kMQTTSessionManager.currentUser.currentBindApsn)
        {
            continue;
        }
        NSString* devRoomName = [dev getRoomName];
        if (devRoomName.length == 0)
        {
            continue;
        }
        BOOL isFind = false;
        [kDataManager roomlistLock];
        for (NSString *roomName in self.m_arrayRoomList)
        {
            if ([roomName isEqualToString:devRoomName])
            {
                isFind = true;
                break;
            }
        }
        [kDataManager roomlistUnlock];
        if (!isFind)
        {
            if( ![devRoomName isEqualToString:@"unknow"])
            {
                RoomModel *room = [[RoomModel alloc]initWithTitle:devRoomName];
                [kDataManager roomlistLock];
                [self.m_arrayRoomList addObject:devRoomName];
                [self roomSave];
                [kDataManager roomlistUnlock];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self addChildController:room];
                    [self deviceDataRefresh];
                });
            }
        }
        [self deviceDataRefresh];
    }
    [kDataManager devlistUnlock];
}
- (void)deviceDataRefresh {
    @synchronized (self) {
        for (UIViewController *vc in self.childViewControllers) {
            DrawingViewController *drawingVc = (DrawingViewController *)vc;
            [drawingVc dataRefresh];
        }
    }
}


- (void)freshRoom
{
    [kDataManager devlistLock];
    for (ZTDevice *dev in kDataManager.deviceListenList)
    {
        if (dev.apsn != kMQTTSessionManager.currentUser.currentBindApsn)
        {
            continue;
        }
        NSString* devRoomName = [dev getRoomName];
        if (devRoomName.length == 0)
        {
            continue;
        }
        BOOL isFind = false;
        for (NSString *roomName in self.m_arrayRoomList)
        {
            if ([roomName isEqualToString:devRoomName])
            {
                isFind = true;
                break;
            }
        }
        if (!isFind)
        {
            if( ![devRoomName isEqualToString:@"unknow"])
            {
                RoomModel *room = [[RoomModel alloc]initWithTitle:devRoomName];
                [self.m_arrayRoomList addObject:devRoomName];
                [self roomSave];
                [self addChildController:room];
                [self deviceDataRefresh];
            }
        }
        [self deviceDataRefresh];
    }
    [kDataManager devlistUnlock];
}



#pragma mark - Notification

- (void)removeRoomNotif:(NSNotification *)notif
{
    self.m_arrayRoomList = [[self roomList] mutableCopy];
    [self removeAllChildControllers];
    NSInteger index = 0;
    for (NSString* room in self.m_arrayRoomList)
    {
        DrawingViewController *vc = [[DrawingViewController alloc] init];
        vc.title = room;
        vc.index = index;
        [self addChildViewController:vc];
        index++;
    }
    [self refreshDisplay];
    [self devNameChangeRefresh:kDataManager];
}

- (void)addRoomNotif:(NSNotification *)notif
{
    
    self.m_arrayRoomList = [[self roomList] mutableCopy];
    [self removeAllChildControllers];
    NSInteger index = 0;
    for (NSString* room in self.m_arrayRoomList) {
        DrawingViewController *vc = [[DrawingViewController alloc] init];
        vc.title = room;
        vc.index = index;
        [self addChildViewController:vc];
        index++;
    }
    [self refreshDisplay];
    [self devNameChangeRefresh:kDataManager];
}

#pragma mark - event response
- (void)switchGatewayHandle
{
    [self removeAllChildControllers];
    [kDataManager roomlistLock];
    self.m_arrayRoomList = nil;
    self.m_arrayRoomList = [[self roomList] mutableCopy];
    NSInteger index = 0;
    for (NSString* room in self.m_arrayRoomList)
    {
        DrawingViewController *vc = [[DrawingViewController alloc] init];
        vc.title = room;
        vc.index = index;
        [self addChildViewController:vc];
        index++;
    }
    [kDataManager roomlistUnlock];
    [self refreshDisplay];
    [self devNameChangeRefresh:kDataManager];
}
- (void)guideImgTapped
{
    [self.guideView removeFromSuperview];
    self.guideView = nil;
}
- (void)searchGateway
{
    ConnectGatewayController *connectNetwayVc = [[ConnectGatewayController alloc]init];
    [self.navigationController pushViewController:connectNetwayVc animated:YES];
}
- (void)didTappedScanButttonItem
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status)
    {
        case AVAuthorizationStatusNotDetermined:
        {
            __weak typeof(self) wself = self;
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        __strong typeof(wself)sself = wself;
                        if (!sself) {
                            return;
                        }
                        [sself entertoQrCodeVC];
                    });
                } else {
                    debugLogInfo(@"用户拒绝");
                }
            }];
        }
            break;
        case AVAuthorizationStatusAuthorized:
        {
            // 已经开启授权，可继续
            [self entertoQrCodeVC];
        }
            break;
        case AVAuthorizationStatusDenied:
        {
            UIAlertView* alerView = [[UIAlertView alloc]initWithTitle:@"相机权限未开启" message:@"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能" delegate:self cancelButtonTitle:@"好" otherButtonTitles:@"设置", nil];
            [alerView show];
        }
            break;
        case AVAuthorizationStatusRestricted:
        {
            [self.view yh_showMsgHUD:@"相机设备无法访问"];
        }
            break;
        default:
            break;
    }
}
- (void)enterMeController {
    MeViewController *meVc = [[MeViewController alloc]init];
    [self.navigationController pushViewController:meVc animated:YES];
}

- (void)titleClick:(UITapGestureRecognizer *)tapGres {
    // 记录是否点击标题
    self.isClickTitle = YES;
    // 获取对应标题label
    UILabel *label = (UILabel *)tapGres.view;
    NSInteger i = label.tag;
    [self selectLabel:label];
    CGFloat offsetX = i * kScreenWidth;
    self.contentScrollView.contentOffset = CGPointMake(offsetX, 0);
    self.lastOffsetX = offsetX;
    self.selIndex = i;
    self.isClickTitle = NO;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0) {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

#pragma mark - UIScrollViewDelegate
// 减速完成
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    // 获取角标
    NSInteger i = offsetX / kScreenWidth;
    // 选中标题
    [self selectLabel:self.titleLabels[i]];
}
// 监听滚动动画是否完成
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    self.isAniming = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 点击和动画的时候不需要设置
    if (self.titleLabels.count == 0) return;
    // 获取偏移量
    CGFloat offsetX = scrollView.contentOffset.x;
    // 获取左边角标
    NSInteger leftIndex = offsetX / kScreenWidth;
    // 左边按钮
    UILabel *leftLabel = self.titleLabels[leftIndex];
    // 右边角标
    NSInteger rightIndex = leftIndex + 1;
    // 右边按钮
    UILabel *rightLabel = nil;
    if (rightIndex < self.titleLabels.count) {
        rightLabel = self.titleLabels[rightIndex];
    }
    // 设置下标偏移
    [self setUpUnderLineOffset:offsetX rightLabel:rightLabel leftLabel:leftLabel];
    // 记录上一次的偏移量
    _lastOffsetX = offsetX;
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.childViewControllers.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kZTRoomCellReuseIdentifierID forIndexPath:indexPath];
    // 移除之前的子控件
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    DrawingViewController *vc = self.childViewControllers[indexPath.item];
    vc.view.frame = cell.contentView.bounds;
    [cell.contentView addSubview:vc.view];
    return cell;
}

#pragma mark - private method

- (void)entertoQrCodeVC {
    UIStoryboard *currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    QRCoderViewController *QRCoderVc = [currentBoard instantiateViewControllerWithIdentifier:@"QRCoderView"];
    QRCoderVc.enterVcType = EnterScanControllerTypeAddGateWay;
    [self.navigationController pushViewController:QRCoderVc animated:YES];
}

- (void)showOfflineMessage {
    if (kDataManager.bindGateModels.count == 0) {
        return;
    }
    for (ZTGatewayBindModel* model in kDataManager.bindGateModels) {
        [YSHUD showGatewayPermit:model];
    }
    [kDataManager.bindGateModels removeAllObjects];
}

- (void)setupNotification {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addRoomNotif:) name:kZTAddNewRoomNotifKey object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeRoomNotif:) name:kZTRemoveRoomNotifKey object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(switchGatewayHandle) name:kZTSwitchGatewayNotifKey object:nil];
}

- (void)initSubviews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.titleScrollView];
    [self.contentView insertSubview:self.contentScrollView belowSubview:self.titleScrollView];
    [self.view addSubview:self.mViewUnboundGateway];
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews {
    // 初始化标题高度
    self.titleHeight = kIphoneSize_Height( kTitleScrollViewH);
    self.titleScrollView.frame = CGRectMake(0, 0, kScreenWidth,self.titleHeight);
    [self.navigationBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(self.view);
        make.height.mas_equalTo(64);
    }];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.navigationBar.bottom);
    }];
    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleScrollView.bottom);
        make.leading.trailing.bottom.equalTo(self.contentView);
    }];
    [self.mViewUnboundGateway mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
}

- (void)initAllViewController {
    [self.m_arrayRoomList enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DrawingViewController *vc = [[DrawingViewController alloc] init];
        vc.title = obj;
        vc.index = idx;
        [self addChildViewController:vc];
    }];
    if (self.childViewControllers.count == 0) return;
    [self setUpTitleWidth];
    [self setUpAllTitle];
}


- (void)setUpTitleWidth {
    NSInteger count = self.childViewControllers.count;
    NSArray *titles = [self.childViewControllers valueForKey:@"title"];
    CGFloat  totalWidth = 0;
    //计算宽度
    for (NSString *title in titles) {
        if ([title isKindOfClass:[NSNull class]]) {
            NSException *excp = [NSException exceptionWithName:@"HomeViewControllerException" reason:@"没有设置Controller.title属性，应该把子标题保存到对应子控制器中" userInfo:nil];
            [excp raise];
        }
        CGRect titleBounds = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options: NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.titleFont} context:nil];
        CGFloat width = titleBounds.size.width;
        [self.titleWidths addObject:@(width)];
        totalWidth += width;
    }
    if (totalWidth > kScreenWidth) {
        self.titleMargin = margin;
        self.titleScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, self.titleMargin);
        return;
    }
    CGFloat titleMargin = (kScreenWidth - totalWidth) / (count + 1);
    self.titleMargin = titleMargin < margin? margin: titleMargin;
    self.titleScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, self.titleMargin);
}

- (void)setUpAllTitle {
    // 遍历所有的子控制器
    NSUInteger count = self.childViewControllers.count;
    // 添加所有的标题
    CGFloat labelW = 0;
    CGFloat labelH = self.titleHeight;
    CGFloat labelX = 0;
    CGFloat labelY = 0;
    for (NSInteger i = 0; i < count; i++) {
        UIViewController *vc = self.childViewControllers[i];
        UILabel *label = [[UILabel alloc] init];
        label.userInteractionEnabled = YES;
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = i;
        label.textColor = [UIColor blackColor];
        label.font = self.titleFont;
        label.text = vc.title;
        labelW = [self.titleWidths[i] floatValue];
        UILabel *lastLabel = [self.titleLabels lastObject];
        labelX = self.titleMargin + CGRectGetMaxX(lastLabel.frame);
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        // 监听标题的点击
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleClick:)];
        [label addGestureRecognizer:tap];
        [self.titleLabels addObject:label];
        [self.titleScrollView addSubview:label];
        if (i == _selectIndex) {
            [self titleClick:tap];
        }
    }
    // 设置标题滚动视图的内容范围
    UILabel *lastLabel = self.titleLabels.lastObject;
    self.titleScrollView.contentSize = CGSizeMake(CGRectGetMaxX(lastLabel.frame), 0);
}

- (void)refreshGateway {
    if (kMQTTSessionManager.currentGateway.name.length != 0) {
        self.titleItem.title = kMQTTSessionManager.currentGateway.name;
    } else {
        self.titleItem.title = @"宇数智能家居";
    }
    self.mViewUnboundGateway.hidden = kMQTTSessionManager.currentUser.currentBindApsn;
}
- (void)initFirstGuideMe {
    if([CommonUtils isNewUpdateWithKey:@"firstLaunchGuideMe"] ) {
        //第一次启动
//        [self addGuideMe];
    } else {
        //不是第一次启动了
    }
}

- (void)addGuideMe {
    UIView* v =  [self.navigationItem.leftBarButtonItem valueForKey:@"view"];
    CGRect rect = [self.navigationController.view  convertRect:v.frame fromView:v.superview];
    CGPoint center =[self.navigationController.view convertPoint:v.center fromView:v.superview];
    self.leftBtnbackgroundView.bounds  = CGRectMake(0, 0, rect.size.width * 1.4, rect.size.height * 1.4);
    self.leftBtnbackgroundView.center = center;
    [self.guideBackgroundView addSubview:self.leftBtnbackgroundView];
    [self.leftBtnbackgroundView addSubview:self.leftBtnImageView];
    self.leftBtnImageView.bounds  = CGRectMake(0, 0, rect.size.width, rect.size.height);
    self.leftBtnImageView.center = CGPointMake(self.leftBtnbackgroundView.bounds.size.width * 0.5, self.leftBtnbackgroundView.bounds.size.height * 0.5);
    [[UIApplication sharedApplication].keyWindow addSubview:self.guideView];
    [self.guideView addSubview:self.guideBackgroundView];
    [self.guideBackgroundView addSubview:self.guideImg];
    [self.guideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo([UIApplication sharedApplication].keyWindow);
    }];
    [self.guideBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.guideView);
    }];
    [self.guideImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.leftBtnbackgroundView);
        make.leading.equalTo(self.leftBtnbackgroundView.trailing);
        make.width.equalTo(kIphoneSize_Widith(199));
        make.height.equalTo(kIphoneSize_Height(249));
    }];
}

- (void)addChildController:(RoomModel *)room {
    DrawingViewController *vc = [[DrawingViewController alloc] init];
    vc.title = room.name;
    vc.dataSource = room.devices;
    vc.index = self.childViewControllers.count;
    [self addChildViewController:vc];
    [self refreshDisplay];
}

- (void)refreshDisplay {
    if (self.childViewControllers.count == 0)
    {
        @throw [NSException exceptionWithName:@"ZT_ERROR" reason:@"请确定添加了所有子控制器" userInfo:nil];
    }
    // 清空之前所有标题
    [self.titleLabels makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.titleLabels removeAllObjects];
    [self.titleWidths removeAllObjects];
    // 重新设置标题
    [self setUpTitleWidth];
    [self setUpAllTitle];
    // 默认选中标题
    self.selectIndex = self.selectIndex;
    [self.contentScrollView reloadData];
}
- (void)selectLabel:(UILabel *)label
{
    for (UILabel *labelView in self.titleLabels) {
        if (label == labelView) continue;
        labelView.textColor = [UIColor blackColor];
    }
    // 修改标题选中颜色
    label.textColor = RGBColor(0, 169, 253);
    // 设置标题居中
    [self setLabelTitleCenter:label];
    // 设置下标的位置
    [self setUpUnderLine:label];
}
// 让选中的按钮居中显示
- (void)setLabelTitleCenter:(UILabel *)label {
    CGFloat offsetX = label.center.x - kScreenWidth * 0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = self.titleScrollView.contentSize.width - kScreenWidth + _titleMargin;
    if (maxOffsetX < 0) {
        maxOffsetX = 0;
    }
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    // 滚动区域
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}
// 设置下标的位置
- (void)setUpUnderLine:(UILabel *)label {
    CGRect titleBounds = [label.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
    CGFloat underLineH = 2;
    self.underLine.yh_y = label.yh_height - underLineH;
    self.underLine.yh_height = underLineH;
    // 最开始不需要动画
    if (self.underLine.yh_x == 0) {
        self.underLine.yh_width = titleBounds.size.width;
        self.underLine.yh_x = label.yh_x;
        return;
    }
    // 点击时候需要动画
    [UIView animateWithDuration:0.25 animations:^{
        self.underLine.yh_width = titleBounds.size.width;
        self.underLine.yh_x = label.yh_x;
    }];
}
// 设置下标偏移
- (void)setUpUnderLineOffset:(CGFloat)offsetX rightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel {
    if (_isClickTitle) return;
    // 获取两个标题中心点距离
    CGFloat centerDelta = rightLabel.yh_x - leftLabel.yh_x;
    // 标题宽度差值
    CGFloat widthDelta = [self widthDeltaWithRightLabel:rightLabel leftLabel:leftLabel];
    // 获取移动距离
    CGFloat offsetDelta = offsetX - _lastOffsetX;
    // 计算当前下划线偏移量
    CGFloat underLineTransformX = offsetDelta * centerDelta / kScreenWidth;
    // 宽度递增偏移量
    CGFloat underLineWidth = offsetDelta * widthDelta / kScreenWidth;
    self.underLine.yh_width += underLineWidth;
    self.underLine.yh_x += underLineTransformX;
}

// 获取两个标题按钮宽度差值
- (CGFloat)widthDeltaWithRightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel {
    CGRect titleBoundsR = [rightLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
    CGRect titleBoundsL = [leftLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
    
    return titleBoundsR.size.width - titleBoundsL.size.width;
}

- (void)removeAllChildControllers {
    for (UIViewController* vc in self.childViewControllers)
    {
        [vc.view removeFromSuperview];
        [vc removeFromParentViewController];
    }
}

- (NSArray*)roomList {
    NSString *roomPath = [MQTTSessionManager roomListPath];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:roomPath];
}

#pragma mark - getters and setters
- (UIView *)underLine {
    if (!_underLine )
    {
        UIView *underLineView = [[UIView alloc] init];
        underLineView.backgroundColor = RGBColor(0, 169, 253);
        [self.titleScrollView addSubview:underLineView];
        _underLine = underLineView;
    }
    return _underLine;
}

- (UIFont *)titleFont {
    if (!_titleFont) {
        _titleFont = kTitleFont;
    }
    return _titleFont;
}

- (NSMutableArray *)titleWidths {
    if (_titleWidths == nil) {
        _titleWidths = [NSMutableArray array];
    }
    return _titleWidths;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc]init];
    }
    return _contentView;
}

- (UIScrollView *)titleScrollView {
    if (!_titleScrollView ) {
        _titleScrollView = [[UIScrollView alloc]init];
        _titleScrollView.backgroundColor = [UIColor whiteColor];
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        _titleScrollView.showsVerticalScrollIndicator = NO;
    }
    return _titleScrollView;
}

- (HomeFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[HomeFlowLayout alloc]init];
    }
    return _flowLayout;
}

- (UICollectionView *)contentScrollView {
    if (!_contentScrollView) {
        _contentScrollView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _contentScrollView.pagingEnabled = YES;
        _contentScrollView.showsHorizontalScrollIndicator = NO;
        _contentScrollView.showsVerticalScrollIndicator = NO;
        _contentScrollView.bounces = NO;
        _contentScrollView.delegate = self;
        _contentScrollView.dataSource = self;
         [_contentScrollView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kZTRoomCellReuseIdentifierID];
    }
    return _contentScrollView;
}

- (NSMutableArray *)titleLabels {
    if (_titleLabels == nil) {
        _titleLabels = [NSMutableArray array];
    }
    return _titleLabels;
}

- (NSMutableArray *)m_arrayRoomList {
    if (!_m_arrayRoomList) {
        NSString *roomPath = [MQTTSessionManager roomListPath];
        NSArray *arrayRooms = [NSKeyedUnarchiver unarchiveObjectWithFile:roomPath];
        if (arrayRooms.count == 0)
        {
            _m_arrayRoomList = [NSMutableArray arrayWithObjects:@"客厅",@"卧室", nil];
            [self roomSave];
        }
        else
        {
            _m_arrayRoomList = [NSMutableArray arrayWithArray:arrayRooms];
        }
    }
    return _m_arrayRoomList;
}

- (UnboundGatewayView *)mViewUnboundGateway {
    if (!_mViewUnboundGateway) {
        _mViewUnboundGateway = [[UnboundGatewayView alloc]init];
        _mViewUnboundGateway.hidden = kMQTTSessionManager.currentUser.currentBindApsn;
        __weak typeof(self)wself = self;
        _mViewUnboundGateway.gatewaySearch = ^() {
            __strong typeof(wself)sself = wself;
            if (!sself)
            {
                return ;
            }
            [sself searchGateway];
        };
    }
    return _mViewUnboundGateway;
}

- (void)roomSave {
    NSString *roomPath = [MQTTSessionManager roomListPath];
    [NSKeyedArchiver archiveRootObject:self.m_arrayRoomList toFile:roomPath];
}

- (UIView *)guideView {
    if (!_guideView) {
        _guideView = [[UIView alloc]init];
    }
    return _guideView;
}

- (UIView *)guideBackgroundView {
    if (!_guideBackgroundView) {
        _guideBackgroundView = [[UIView alloc]init];
        _guideBackgroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    }
    return _guideBackgroundView;

}

- (UIImageView *)guideImg {
    if (!_guideImg) {
        _guideImg = [[UIImageView alloc]init];
        _guideImg.image = [UIImage imageNamed:@"home_guide_me"];
        _guideImg.userInteractionEnabled = YES;
        UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(guideImgTapped)];
        [_guideImg addGestureRecognizer:tapGesture];
    }
    return _guideImg;

}

- (UIView *)leftBtnbackgroundView {
    if (!_leftBtnbackgroundView) {
        _leftBtnbackgroundView = [[UIView alloc]init];
        _leftBtnbackgroundView.backgroundColor = [UIColor whiteColor];
    }
    return _leftBtnbackgroundView;

}
- (UIImageView *)leftBtnImageView
{
    if (!_leftBtnImageView) {
        _leftBtnImageView = [[UIImageView alloc]init];
        _leftBtnImageView.image = [UIImage imageNamed:@"home_icon_me"];
    }
    return _leftBtnImageView;
}

- (UINavigationBar *)navigationBar
{
    if (!_navigationBar) {
        _navigationBar = [[UINavigationBar alloc]init];
        [_navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBarbackgroundImage"] forBarMetrics:UIBarMetricsDefault];
        NSMutableDictionary *barTextAttrs = [NSMutableDictionary dictionary];
        barTextAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
        barTextAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:17];
        [_navigationBar setTitleTextAttributes:barTextAttrs];
        _navigationBar.items = @[self.titleItem];
    }
    return _navigationBar;
}
- (UINavigationItem *)titleItem
{
    if (!_titleItem) {
        _titleItem = [[UINavigationItem alloc]init];
        _titleItem.leftBarButtonItem = [UIBarButtonItem createBarbuttonItem:@"home_icon_me" target:self action:@selector(enterMeController)];
        _titleItem.rightBarButtonItem =  [UIBarButtonItem createBarbuttonItem:@"home_icon_scan" target:self action:@selector(didTappedScanButttonItem)];
        _titleItem.title = @"智能家居";
;
    }
    return _titleItem;
}

@end
